package com.xhblog.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhblog.entity.SysUser;
import com.xhblog.entity.vo.LoginUserVo;
import com.xhblog.enums.ErrorCode;
import com.xhblog.mapper.SysUserMapper;
import com.xhblog.result.Result;
import com.xhblog.service.SysUserService;
import com.xhblog.utils.JwtUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author pengyouhong
 * create 2022/5/17 18:11
 */
@Service
@Log4j2
@Lazy
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public SysUser findUser(String account, String password) {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();

        /*
         * select * from sysUser where account=#{account} and password=#{password}
         * */
        sysUserLambdaQueryWrapper
                .eq(SysUser::getAccount, account)
                .eq(SysUser::getPassword, password);

        return baseMapper.selectOne(sysUserLambdaQueryWrapper);
    }

    @Override
    public Result findUserByToken(String token) {
        /*
         * 1.token合法性校验
         * 是否为空，解析是否成功 redis中是否存在
         * 如果成功,返回对应的结果 LoginUserVo
         * */


        SysUser sysUser = checkToken(token);


        if (sysUser == null) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }

        log.info(sysUser);

        LoginUserVo loginUserVo = new LoginUserVo();

        BeanUtils.copyProperties(sysUser, loginUserVo);

        return Result.success(loginUserVo);
    }

    /**
     * 检查token
     *
     * @param token token
     * @return 返回用户信息 ，如果token不合法，返回null
     */
    public SysUser checkToken(String token) {

        //如果token为null,则返回null
        if (StringUtils.isBlank(token)) {
            return null;
        }

        Map<String, Object> map = JwtUtils.checkToken(token);

        //检验token是否合法
        if (map == null) {
            return null;
        }

        String userJson = redisTemplate.opsForValue().get("TOKEN" + token);

        return JSON.parseObject(userJson, SysUser.class);
    }
}
